
package guoan.service.weixin;

import guoan.core.configuration.WeiXinCfgBean;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

import org.jeewx.api.core.exception.WexinReqException;
import org.jeewx.api.core.req.model.menu.WeixinButton;
import org.jeewx.api.wxbase.wxmedia.JwMediaAPI;
import org.jeewx.api.wxbase.wxmedia.model.WxUpload;
import org.jeewx.api.wxbase.wxtoken.JwTokenAPI;
import org.jeewx.api.wxmenu.JwMenuAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;

import com.google.common.cache.Cache;

@Service
public class WeiXinService {

    protected final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private WeiXinCfgBean weiXinCfgBean;

    @Autowired(required = false)
    @Qualifier("accessTokenCache")
    private Cache<String, String> accessTokenCache;

    /**
     * @Title：getAccessToken
     * @Description: 7000秒后，自动获取AccessToken
     * @author Administrator
     * @date 2015年5月5日 上午11:07:45
     * @return
     * @throws ExecutionException
     * @throws WexinReqException
     */
    public String getAccessToken(){

        try {
            // Callable只有在缓存值不存在时，才会调用
            String accessToken = accessTokenCache.get("accessTokenCache",
                    new Callable<String>() {
                        @Override
                        public String call() throws Exception{
                            return JwTokenAPI.getAccessToken(
                                    weiXinCfgBean.getAppid(),
                                    weiXinCfgBean.getAppscret());

                        }
                    });
            log.info("accessToken <- {}", accessToken);
            return accessToken;
        } catch (ExecutionException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @Title：getAllMenu
     * @Description: 获得微信菜单
     * @author Administrator
     * @date 2015年5月5日 上午11:15:22
     * @return
     */
    public List<WeixinButton> getAllMenu(){
        List<WeixinButton> weixinButtons = null;
        try {
            int i = 0;
            while (i < 20) {
                weixinButtons = JwMenuAPI.getAllMenu(getAccessToken());
                if (weixinButtons == null) {
                    accessTokenCache.invalidateAll();
                    i++;
                } else {
                    break;
                }
            }

            log.info("weixinButtons <- {}", weixinButtons);
        } catch (WexinReqException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new RestClientException("微信通讯错误", e);
        }
        return weixinButtons;
    }

    public WxUpload uploadMedia(String type, String fileNamePath){
        WxUpload wxu = null;
        try {
            int i = 0;
            while (i < 20) {
                wxu = JwMediaAPI.uploadMedia(getAccessToken(), type,
                        fileNamePath);
                if (wxu == null) {
                    accessTokenCache.invalidateAll();
                    i++;
                } else {
                    break;
                }
            }
            log.info("WxUpload <- {}", wxu);
            return wxu;
        } catch (WexinReqException e) {
            // TODO Auto-generated catch block
            throw new RestClientException("微信通讯错误", e);
        }
    }

    public String createMenu(List<WeixinButton> buttons){
        String msg = null;
        try {
            int i = 0;
            while (i < 20) {
                msg = JwMenuAPI.createMenu(getAccessToken(), buttons);
                if (msg == null) {
                    accessTokenCache.invalidateAll();
                    i++;
                } else {
                    break;
                }
            }
            log.info("createMenu <- {}", msg);
            return msg;
        } catch (WexinReqException e) {
            // TODO Auto-generated catch block
            throw new RestClientException("微信通讯错误", e);
        }
    }
}
